package com.crm.controller.sourceController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.mail.AuthenticationFailedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartSourcesDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.SourceInfoDAO;
import com.crm.dao.SourcesDAO;
import com.crm.entity.Business;
import com.crm.entity.Clientdet;
import com.crm.entity.Opportunity;
import com.crm.entity.PartSources;
import com.crm.entity.Parts;
import com.crm.entity.Sources;
import com.crm.entity.User;
import com.crm.util.Constants;
import com.crm.util.SendMail;


	@Controller
	@RequestMapping("/exportsource")
	public class ExpToSrcController {
		protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping( "/open.do") 
	public ModelAndView insert(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
			int busid=bus.getBusinessId();
			
			User u=(User)session.getAttribute("user");
			System.out.println("Email is:"+u.getEmail()+" Password is:"+u.getPassword());
			logger.info("Email is:"+u.getEmail()+" Password is:"+u.getPassword());
			if(u.getEmail()==null || u.getPassword()==null){
				return new ModelAndView("/jsp/Users.jsp","command",u)
				.addObject("menuName","admin")
				.addObject("submenu","admin")
				.addObject("msg","Please Enter Your Email ID And Password Correctly");
			}
			
			 String status=Constants.ST_PENDING;
			//OpportunityDAO oprD=new OpportunityDAO();
				List<Opportunity> opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getByStatus(status, busid);
					logger.info("opportunity list is "+opr);
			  model = new ModelAndView("/jsp/exportSource.jsp");
				model.addObject("opprtunity",opr);
			 if(request.getAttribute("selectedRef")!=null){
					String refno=request.getAttribute("selectedRef").toString();
					model.addObject("selectedRef",refno);
			 }
			 String currentref=request.getParameter("currentref");
			 System.out.println("the current refnois"+currentref);
				model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");
		 
				return model;
	}
	@RequestMapping( "/search.do") 
	public ModelAndView search(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("redirect:/jsp/index.jsp");
		
		String ref=req.getParameter("refno");
		logger.info("refno is "+ref);
			PartsDAO PrtsD=new PartsDAO();
			//OpportunityDAO op=new OpportunityDAO();
			Opportunity o=OpportunityDAO.getSingleInstance().getByRef(ref,bus.getBusinessId());
			
			Clientdet clientdet=null;
			clientdet=o.getClientId();
					List<Parts> opr=(List<Parts>)PrtsD.getParts(ref,bus.getBusinessId());
					logger.info("Parts list is "+opr);
					SourcesDAO sDAO=new SourcesDAO();
					List<Sources> sourcelist=sDAO.findAll(bus.getBusinessId());
					logger.info("sourcelist is "+sourcelist);
					model = new ModelAndView("/jsp/exportSourceRes.jsp");
					clientdet.setDivision(o.getDivision());
					//clientdet.setCliuser(o.getUser());
					System.out.println("the client is"+o.getDivision());
					System.out.println("the client is"+o.getUser());
				model.addObject("client",clientdet)	;
				model.addObject("user",o.getUser())	;
				model.addObject("partslist",opr);
				model.addObject("slist",sourcelist);
				
			return model;
	}
	@RequestMapping( "/save.do") 
	public ModelAndView save(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		try{
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			int busid=bus.getBusinessId();
			//OpportunityDAO op=new OpportunityDAO();
			SourceInfoDAO sid=new SourceInfoDAO();
			PartSourcesDAO partsrc=new PartSourcesDAO();
			SourcesDAO sd=new SourcesDAO();
			PartsDAO p=new PartsDAO();
			String ref=request.getParameter("reflist");
			logger.info("refno in Export to Source Controller is: "+ref);
			String srowCount=request.getParameter("rowCount");
			
			Opportunity o=OpportunityDAO.getSingleInstance().getByRef(ref,bus.getBusinessId());
			if(srowCount!=null && srowCount!="0"){
			int rowCount=Integer.parseInt(srowCount);
			
			
			try {
				
				sid.deleteSourceWithEnq(o.getId(),bus.getBusinessId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			List<Sources> ls=sd.findAll(bus.getBusinessId());
			try{
				partsrc.deletePrtSrcInfo(o.getId(),bus.getBusinessId());
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			List<PartSources> lps=new ArrayList<PartSources>();
			PartSources ps=null;
			for(int j=0;j<ls.size();j++){
			for(int i=0;i<rowCount;i++){
				String partNumber=request.getParameter("part"+(i+1));
				logger.info("Part name IN EXPTOSRC Controller Is:"+partNumber);
				//String desc=request.getParameter("desc"+(i+1));
				String partid=request.getParameter("partid"+(i+1));
				System.out.println("partnum is"+partid);
				int id=Integer.parseInt(partid);
				System.out.println("partid is"+id);
				
			
				String sourceName=request.getParameter(ls.get(j).getSourceName()+(i+1));
				logger.info("Source Array is:"+sourceName);
				
				if (sourceName!=null) {
					ps=new PartSources();
					logger.info("Source Name Is:"+sourceName);
					Parts par=p.findById(id,bus.getBusinessId(),o.getId());
					ps.setEnqid(o.getId());
					ps.setBusinessId(bus);
					ps.setPartid(par);
					ps.setSourceid(ls.get(j).getId());
					ps.setMailSent(false);
					ps.setSourceCompleted(false);
					logger.info("Parts Object In ExpoSrc Is:"+ps);
					lps.add(ps);
					}
				}
			
			}
			partsrc.saveList(lps);
			logger.info("List Of Sources Is:"+ls);
			
			Set<String> slist=sid.setSrc(bus.getBusinessId(),ref);
			
			model = new ModelAndView("redirect:/importsource/show.do");
			model.addObject("importsrc","SuccessFully Exported To Sources");
			model.addObject("currentref",ref);
			model.addObject("sources",slist);
			String s=Constants.ST_SOURCE_INFO_SENT;
			OpportunityDAO.getSingleInstance().updateStatus(busid,s, o.getId());
			boolean status=false;
			OpportunityDAO.getSingleInstance().isSourceCompleted(o.getId(), status,bus.getBusinessId());
			}else{
				model.addObject("importsrc","No Rows TO Export");
			}
			return model;
			
		}catch(Exception e){
			model = new ModelAndView("redirect:show.do");
			model.addObject("importsrc","An Exception Occured while exporting to Source");
			logger.info("Exception Occured When Exporting To Source in save.do");
			e.printStackTrace();
			return model;
		}
	}
	@RequestMapping( "/setMail.do") 
	public ModelAndView setMail(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		try{
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			int busid=bus.getBusinessId();
				String str=request.getParameter("sourceid");
				SourcesDAO sd=new SourcesDAO();
				SourceInfoDAO sidao=new SourceInfoDAO();
				//OpportunityDAO odao=new OpportunityDAO();
				int sid=sd.getByName(str.trim(),bus.getBusinessId()).getId();
				
				String refNo=request.getParameter("refno");
				System.out.println("Ref No In SetMail.do Is :"+refNo);
				
				
				int rfNo=OpportunityDAO.getSingleInstance().getOpportunityByRefNo(refNo,bus.getBusinessId()).getId();
				logger.info("REF N0 "+rfNo);
				List<Parts> lp=sidao.getPartsName(rfNo,sid,bus.getBusinessId());
				List<Sources> ls=sd.findAll(bus.getBusinessId());
				logger.info("list parts "+lp);
				
				
				PartSourcesDAO psdao=new PartSourcesDAO();
				List<PartSources> lpso=psdao.getMailNotSentSources(rfNo,busid);
				Set<Sources> lso=new HashSet<Sources>();
				Iterator<PartSources> it=lpso.iterator();
				while(it.hasNext()){
					PartSources partso=(PartSources)it.next();
					int sourceid=partso.getId();
					Sources so=sd.findById(sourceid, busid);
					lso.add(so);
				}
				
				
				
				model = new ModelAndView("/jsp/sendMailPopUp.jsp?reflsit="+refNo);
				
				model.addObject("partsList",lp);
			
				model.addObject("soName",str);
				model.addObject("SourceList",ls);
				model.addObject("reflist",refNo);
				logger.info("Reference Number Is:"+refNo);
				model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");
				model.addObject("soList",lso);
			
				return model;
		}catch(Exception e){
			System.out.println("An Exception Occured when setting mail In SetMail.do");
			e.printStackTrace();
			return model;
		}
	}
	@RequestMapping( "/sendMail.do") 
	public ModelAndView sendMail(HttpServletRequest request,HttpSession session, ModelAndView model){
		try{
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			User u=(User)session.getAttribute("user");
			String from=u.getEmail();
			System.out.println("User Email Id Is:"+from);
			String pass=u.getEmailPwd();
			System.out.println("User password Is:"+pass);
			System.out.println("Email is:"+from+" Password is:"+pass);
			int busid=bus.getBusinessId();
			SourcesDAO sd=new SourcesDAO();
			PartSourcesDAO psdao=new PartSourcesDAO();
					SendMail sm=new SendMail();
					String sourceName=request.getParameter("sourceName").trim();
					
					Sources s = null;
					try {
						s = sd.getByName(sourceName,bus.getBusinessId());
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					String refno=request.getParameter("refno").trim();
					//OpportunityDAO oppdao=new OpportunityDAO();
					Opportunity op = null;
					try {
						op = OpportunityDAO.getSingleInstance().getByRef(refno, busid);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					logger.info("Refe No In SendMail.do Is:"+refno);
					String soEmail=s.getEmail();
					String sub=request.getParameter("subject");
					String srowCount=request.getParameter("rowCount");
					String enqnum=request.getParameter("enqnum");
					
					
					StringBuilder sb=new StringBuilder();
					sb.append("<h2>Hi</h2><h2>"+sub+"</h2> <br>");
					sb.append("Reference Number Is "+enqnum+"\n");
					sb.append("Due Date Is "+op.getDuedate()+"\n");
					sb.append("<table border=1 width='890'><tr><th width='30'>S.No</th> <th width='200'> Part</th><th width='50'> Quantity</th> <th width='200'> Make</th> <th width='200'> Description </th><th width='200'> Specification </th></tr>" );
					int rowCount=Integer.parseInt(srowCount);
					for(int i=0;i<rowCount;i++){
						logger.info("Part Is: "+request.getParameter("part"+(i+1)));
						String part=request.getParameter("part"+(i+1));
						String qty=request.getParameter("quantity"+(i+1));
						String make=request.getParameter("make"+(i+1));
						String desc=request.getParameter("description"+(i+1));
						String spec=request.getParameter("specification"+(i+1));
						sb.append("<tr><td align='center'>"+(i+1)+"</td><td>"+part+"</td><td align='center'>"+qty+"</td><td>"+make+"</td><td>"+desc+"</td><td>"+spec+"</td></tr>");
						
					}
					sb.append("</table>");
					sb.append("<br><h3>Thanks & Regards</h3>");
					sb.append("<h4>"+u.getFirstName()+" "+u.getLastName()+"</h4>");
					sb.append("<br><h4>Operations Manager</h4>");
					sb.append("<br><h4>"+bus.getBusinessName()+"</h4>");
					
					File file = null;
					byte[] logo=null;
					MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
					MultipartFile fileUpload = multipartRequest.getFile("attachment");
					
					
					
					String fileName=new String();
					String message=null;
					if(fileUpload!=null){
						System.out.println("In If Block");
						try {
							logo = fileUpload.getBytes();
							fileName=fileUpload.getOriginalFilename();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						
						try{
							String filePath=session.getServletContext().getRealPath("/WEB-INF")+"/"+fileName;
							file=new File(filePath);
						System.out.println("File Path Is:"+file.getAbsolutePath());
						System.out.println("File Path Is:"+file.getPath());
							file.createNewFile();
							FileOutputStream fos=null;
							if(file != null){
								fos=new FileOutputStream(file);
								fos.write(logo);
								fos.flush();
								fos.close();
							}
						}catch(Exception e){
							e.printStackTrace();
						}
						
						logger.info("The File Name Is:"+fileName);
						try{
							sm.sendMail(from,pass,sb.toString(), sub, soEmail, file, fileName);
							psdao.updateMailSent(op.getId(), s.getId(), busid);
							message="Mail Sent Successfully With File.";
							logger.info("Mail Sent successfully with File "+fileName);
						}catch(AuthenticationFailedException afe){
							afe.printStackTrace();
							message="Your Mail Id Or Password Is Wrong.Please Check";
							logger.info("Email id And password are not valid for user "+u.getEmail());
						}
						catch(Exception e){
							e.printStackTrace();
							message="Mail Sending Failed. Please Try Again";
							logger.info("Unmanaged Exception occured while sending mail from Email id "+u.getEmail());
						}
						
						
					}
				else{
					
					try{
						sm.sendMailNoFile(from,pass,sb.toString(), sub, soEmail,null);
						psdao.updateMailSent(op.getId(), s.getId(), busid);
						logger.info("Mail succesfully send from user "+u.getUserName()+" with emial id "+u.getEmail()+" without file");
						message="Mail Sent Successfully.";
					}catch(AuthenticationFailedException afe){
						afe.printStackTrace();
						message="Your Mail Id Or Password Is Wrong.Please Check";
						logger.info("Email id And password are not valid for user "+u.getEmail());
					}catch(Exception e){
						e.printStackTrace();
						message="Mail Sending Failed. Please Try Again";
						logger.info("Unmanaged Exception occured while sending mail from Email id "+u.getEmail());
					}
					logger.info("Displayed Message Is:"+message);
					
					
				}
					file.delete();
					model = new ModelAndView("/jsp/sendMailPopUp.jsp");
					model.addObject("reflist",refno);
					model.addObject("msg",message);
					return model;
		}catch(Exception e){
			logger.info("An Exception Occured In sending mail in sendmail.do");
			e.printStackTrace();
			return model;
		}
	}
}
